# -*- coding: utf-8 -*-
import os
import re

__author__ = 'raniys'

DEBUG = True

# WORDS_FILE = "words_alpha.txt"
WORDS_FILE = "words.txt"


def log(**kwargs):
    msg = ''
    for k, v in kwargs.items():
        msg += '{}={}, '.format(k, v)
    print msg


def loads_local_words():
    file_directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'english_words')
    word_list = []
    with open(os.path.join(file_directory, WORDS_FILE), "r+") as ins:
        for line in ins.read().splitlines():
            word_list.append(line)
    return word_list


def generate_word_dict(word_list):
    """
    generate word dictionary and alphabet frequency by word length
    :param word_list: list of all the english word from local dictionary library
    :return: two dictionaries: word dictionary, alphabet frequency dictionary
    """
    word_dict = {}
    alphabet_frequency = {}
    for w in word_list:
        word_len = len(w)
        if word_len not in word_dict:
            word_dict[word_len] = []
            alphabet_frequency[word_len] = {}
        word_dict[word_len].append(w)
        for a in w:
            if a not in alphabet_frequency[word_len]:
                alphabet_frequency[word_len][a] = 0
            alphabet_frequency[word_len][a] += 1
    sorted_alphabet_frequency = {}
    for a in alphabet_frequency:
        sorted_alphabet_frequency[a] = sorted(alphabet_frequency[a].items(), key=lambda s: -s[1])
    return word_dict, sorted_alphabet_frequency


def calculate_alphabet_frequency(last_match_words, res, used_chars):
    """
    calculate the alphabet frequency for next match
    :param last_match_words: the last match word list
    :param res: the match result word from server
    :param used_chars: has already used characters
    :return: two dictionaries: word dictionary, alphabet frequency dictionary
    """
    match_words = []
    alphabet_frequency = {}
    a_str = '[' + '|'.join([c for c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' if c not in res and c not in used_chars]) + ']'
    reg_str = res.replace('*', a_str) + '$'
    for w in last_match_words:
        if re.match(reg_str, w):
            valid = True
            for char in w:
                if char in used_chars and char not in res:
                    valid = False
                    break
            if valid:
                match_words.append(w)
                for a in w:
                    if a in res:
                        continue
                    if a not in alphabet_frequency:
                        alphabet_frequency[a] = 0
                    alphabet_frequency[a] += 1
    sorted_alphabet_frequency = sorted(alphabet_frequency.items(), key=lambda s: -s[1])
    return match_words, sorted_alphabet_frequency
